import json
import os
from flask import Flask, request

from chatbot.predict import auto_QA
from chatbot.training_txt import start_train
from chatbot.prepare_dataset_txt import start_prepare_dataset

app = Flask(__name__)


# 预测
@app.route('/robot/dialogue', methods=['POST', 'GET'])
def dialogue():
    result = {
        'code': 400,
        'msg': '失败',
        'data': None
    }
    respData = {
        'flag': 0,
        'say': ''
    }
    query = request.args.get("query")
    if query == '' or query is None:
        result['msg'] = '请输入查询内容'
        result['data'] = respData
        return json.dumps(result, ensure_ascii=False)
    print("问题：", query)
    say = auto_QA(query)
    print("答案：", say)
    respData['say'] = say.replace("\n", "")
    result['code'] = 200
    result['msg'] = '成功'
    result['data'] = respData
    return json.dumps(result, ensure_ascii=False)


# 保存
@app.route('/save/dataset', methods=['POST', 'GET'])
def save_dataset():
    result = {
        'code': 400,
        'msg': ''
    }
    questions = request.args.get("questions")
    answer = request.args.get("answer")
    if questions == '' or questions is None:
        result['msg'] = '请输入问题'
        return json.dumps(result, ensure_ascii=False)
    if answer == '' or answer is None:
        result['msg'] = '请输入答案'
        return json.dumps(result, ensure_ascii=False)
    data_root_path = "./dataset"
    # if os.path.exists(data_root_path + '/dict_txt.txt'):  # 如果文件存在
    #     # 删除文件，可使用以下两种方法。
    #     os.remove(data_root_path + '/dict_txt.txt')
    #     # os.remove(data_root_path + '/test_list.txt')
    #     os.remove(data_root_path + '/train_list.txt')
    # else:
    #     print('no such file:', "dict_txt.txt,train_list.txt")
    # with open(os.path.join(data_root_path, 'train.txt'), 'r', encoding='utf-8') as f_data:
    #     lines = f_data.readlines()
    #     lastLine = lines[len(lines) - 1]
    #     lastLine = lastLine.split("|")[0]
    #     split_questions = questions.split("|")
    # with open(os.path.join(data_root_path, 'train.txt'), 'a', encoding='utf-8') as f_data:
    #     for question in split_questions:
    #         line_ = int(lastLine) + 1
    #         add_question = str(line_) + "|" + question.replace("\n", "")
    #         f_data.write(add_question.strip() + "\n")
    # with open(os.path.join(data_root_path, 'FAQ.txt'), 'r', encoding='utf-8') as f_data:
    #     lines = f_data.readlines()
    #     lastLine = lines[len(lines) - 1]
    #     lastLine = lastLine.split("|")[0]
    # with open(os.path.join(data_root_path, 'FAQ.txt'), 'a', encoding='utf-8') as f_data:
    #     line_ = int(lastLine) + 1
    #     add_answer = str(line_) + "|" + answer.replace("\n", "")
    #     f_data.write(add_answer.strip() + "\n")
    # 生成字典
    start_prepare_dataset()
    result['code'] = 200
    result['msg'] = '添加成功'
    return json.dumps(result, ensure_ascii=False)


# # 训练数据
@app.route('/trainning', methods=['POST', 'GET'])
def train():
    result = {
        'code': 200,
        'msg': '训练成功'
    }
    start_train()
    return json.dumps(result, ensure_ascii=False)


# # # 生成字典
# @app.route('/build/dict', methods=['POST', 'GET'])
# def build_dict():
#     result = {
#         'code': 200,
#         'msg': '生成字典成功'
#     }
#     return json.dumps(result, ensure_ascii=False)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
